package com.mayavi.bc.impl;

import java.sql.Timestamp;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import com.mayavi.bc.ICelebrityBc;
import com.mayavi.bo.CelebrityBo;
import com.mayavi.bo.CelebrityTypeBo;
import com.mayavi.criteria.CelebrityTypeCriteria;
import com.mayavi.dao.ICelebrityDao;
import com.mayavi.dto.CelebrityDto;

public class CelebrityBcImpl implements ICelebrityBc{
	private ICelebrityDao celebrityDao;

	public List<CelebrityBo> getAllCelebrities(){
		return celebrityDao.getAllCelebrities();
	}
	
	public List<CelebrityTypeBo> getAllCelebrityTypes(){
		return celebrityDao.getAllCelebrityTypes();
	}
	
	public CelebrityBo getCelebrityById(Integer id){
		return celebrityDao.getCelebrityById(id);
	}
	
	public void saveCelebrity(CelebrityDto dto){
		Integer id = dto.getId();
		CelebrityBo celebrityBo = null;
		if(id!=null&&id>0){//update
			celebrityBo = celebrityDao.getCelebrityById(id);
		}else {//save
			celebrityBo = new CelebrityBo();
			celebrityBo.setCreationTstamp(new Timestamp(System.currentTimeMillis()));
			celebrityBo.setCreatedByUserId(dto.getModifiedById());
		}
		celebrityBo.setLastModifiedTstamp(new Timestamp(System.currentTimeMillis()));
		celebrityBo.setLastModifiedByUserId(dto.getModifiedById());
		celebrityBo.setFirstName(dto.getFirstName());
		celebrityBo.setMiddleName(dto.getMiddleName());
		celebrityBo.setLastName(dto.getLastName());
		celebrityBo.setAlias(dto.getAlias());
		celebrityBo.setDob(new Timestamp(dto.getDob().getTime()));
		celebrityBo.setIsAlive(dto.getIsAlive());
		celebrityBo.setGender(dto.getGender());
		CelebrityTypeCriteria crit = new CelebrityTypeCriteria();
		crit.setIds(dto.getTypes());
		List<CelebrityTypeBo> types = celebrityDao.getCelebrityTypesByCriteria(crit);
		Map<Integer,CelebrityTypeBo> celebrityTypeMapToAdd = new HashMap<Integer,CelebrityTypeBo>();
		
		for(CelebrityTypeBo celebrityTypeBo:types){
			celebrityTypeMapToAdd.put(celebrityTypeBo.getId(), celebrityTypeBo);
		}
		Iterator it = celebrityBo.getCelebrityTypes().iterator();
		while(it.hasNext()){
			CelebrityTypeBo celebrityTypeBo = (CelebrityTypeBo)it.next();
			if(celebrityTypeMapToAdd.containsKey(celebrityTypeBo.getId())){
				celebrityTypeMapToAdd.remove(celebrityTypeBo.getId());
			} else {
				it.remove();
			}
		}
		celebrityBo.getCelebrityTypes().addAll(celebrityTypeMapToAdd.values());
		celebrityDao.saveCelebrity(celebrityBo);
	}	

	public ICelebrityDao getCelebrityDao() {
		return celebrityDao;
	}

	public void setCelebrityDao(ICelebrityDao celebrityDao) {
		this.celebrityDao = celebrityDao;
	}
}
